const charset = require('superagent-charset');
const superagent =  charset(require('superagent'));
require('superagent-proxy')(superagent);
const sdate = require('silly-datetime');
const fetch = require('node-fetch');
const ProxyAgent = require('proxy-agent');
const HttpsProxyAgent = require("https-proxy-agent");

const got = require('got');

const {
    getTaskPage,
    wxpusher,
} = require('./ti_scan_config');

const {
    readTask,
} = require('./ti_logic_read_task');

const {
    logger,
    sleep,
    httpGet,
    httpPost,
    getProxy,
    getIp,
    getIp_v5,
    getIp_v6,
    httpProxyGet,
    httpProxyGet2,
    httpProxyGet3,
    httpProxyGet4,
    tiGet,
} = require('./util');

const {
    get,
    easyPushWechatMsg,
    lpush,
    set,
    hget,
    hset,
    expire,
    hgetall,
    randBetween,
    avoidNoticeFreq,
    avoidNoticeFreqCookie,
    avoidNoticeFreqByKey,
} = require('../util');

const {
    syncExec,
    syncExec2
} = require('../model'); 

process.on('unhandledRejection', error => {
    //...不处理...
});

const serialMap = {};//已启动到任务

let ip_list = [];

let arguments = process.argv.splice(2);

let process_num = 70;

const updateProxySlow = async () => {

    let key = 'new_proxy_list_'+arguments[0];

    //ip_list = await get(key);

    if(ip_list){
        //ip_list = JSON.parse(ip_list);
    }else{
        ip_list = [];
    }

    let now_time = new Date().getTime();

    

    if(ip_list.length>0){
        for(let m=0; m<ip_list.length; m++){
            if(ip_list[m].expire_time - now_time/1000 <25){
                ip_list.splice(m, 1);
            }
        }
    }

    if(ip_list.length < process_num+45){

        //logger(4444444);
        let new_ip_list = await getIp_v6(2);

        logger('new_ip_list', new_ip_list);

        if(!new_ip_list){
            await sleep(2000);
            new_ip_list = await getIp_v6(2);
        }

        for(let m=0; m<new_ip_list.length; m++){
            ip_list.push(new_ip_list[m]);
        }
    }

    //await set(key, JSON.stringify(ip_list));
}

//每30秒重新拉取任务列表
(async () => {
    while (1) {
        //await updateProxySlow();
        await sleep(10000);
    }
})();



const delete_proxy = async (proxy, serial) => {

    for(let m=0; m<ip_list.length; m++){
        if(ip_list[m].ip == proxy || ip_list[m].serial == serial){
            //ip_list.splice(m, 1);
        }
    }
}

const update_fail_proxy = async (proxy, serial) => {

    for(let m=0; m<ip_list.length; m++){
        if(ip_list[m].ip == proxy || ip_list[m].serial == serial){
            
            if(ip_list[m].fail_num == undefined || ip_list[m].fail_num == 'NAN'){
                ip_list[m].fail_num = 1;
            }else{
                ip_list[m].fail_num = ip_list[m].fail_num + 1;
            }

            if(ip_list[m].fail_num >= 5){
                //  失败超过2次就换ip
                //logger('删除proxy', proxy+' '+serial+' '+ip_list.length)
                //ip_list.splice(m, 1);
                //logger('删除proxy', proxy+' '+serial+' '+ip_list.length)
            }
        }
    }

    for(var j in ip_list){
        if(ip_list[j].serial == '' || ip_list[j].serial == undefined){
            ip_list[j].serial = serial;
            return ip_list[j];
        }
    }

    logger('删除完成');

}


const getProxySlow = async (serial) => {
    let proxy = '';

    let key = 'new_proxy_list_'+arguments[0];

    logger('ip_list', ip_list);

    logger('find_proxy_', serial);

    //ip_list = await get(key);

    if(ip_list){
        //ip_list = JSON.parse(ip_list);
    }else{
        ip_list = [];
    }

    if(ip_list.length == 0){
        return '';
    }

    for(var j in ip_list){
        if(ip_list[j].serial == serial){
            proxy = ip_list[j].ip;
            return ip_list[j];
        }
    }

    

    for(var j in ip_list){
        if(ip_list[j].serial == '' || ip_list[j].serial == undefined){
            ip_list[j].serial = serial;
            proxy = ip_list[j].ip;

            //await set(key, JSON.stringify(ip_list));

            return ip_list[j];
        }
    } 

    //console.log('ip_length', ip_list.length);

    return proxy;
}

//每N秒重新拉取任务列表
(async () => {
    const url = 'https://www.ti.com.cn/storeservices/cart/opninventory?opn=';

    while (1) {

        // const tasks = await readTask(arguments[0],process_num);
        // if (!tasks) {
        //     await sleep(5000);
        //     continue;
        // }

        let serial = 'INA128HD';

        const fullUrl = url + encodeURIComponent(serial);
            let str = '';
            let ret = '';

            let proxyusernm = '11550505';

            let proxypasswd = '12345678';

            str = await Promise.race([
                    httpProxyGet3(fullUrl, 'http://'+proxyusernm+":"+proxypasswd+"@"+'117.81.151.95:57114'),
                    sleep(16000)
                ]);

        logger('str', str);

        return;

        //logger('ip11111');

        //logger('tasks', tasks);

        //const tasks = [{ taskid: 1, taskId: 1, serial: 'INA128HD', status: 1 }];

        //console.log(tasks);

        //logger('start');

        //var proxy = '';

        //let agent = new ProxyAgent('http://183.165.247.226:64256');

        //const agent = new HttpsProxyAgent('http://114.236.24.96:64257');

        //var str = '';

        // var str = await fetch("https://xxproperty.shenzhenbenwo.com/api/Cloudfile/index", {
        //   "headers": {
        //     "cookie": "_ga=GA1.3.477390357.1626857730; ELOQUA=GUID=F915935CD92F4B76B042F6C1601243C6; __adroll_fpc=173589a121e46c49026661b8d685e18d-1626857998685; CONSENTMGR=ts:1633675597897%7Cconsent:true; coveo_visitorId=f2690004-af71-4488-8ae1-835dfb89e48e; _gcl_au=1.1.57629291.1635065929; tiSessionID=lita4c81440a4c81440a4c8144061751ec3340c8ffe; user_pref_shipTo=\"CN\"; user_pref_currency=\"CNY\"; _fbp=fb.2.1636048547960.508365719; user_pref_language=\"zh-CN\"; alias=sys-null-null-cninfra_uhv-bhp-pp-null-cn; ti_ua=Mozilla%2f5.0%20(Macintosh%3b%20Intel%20Mac%20OS%20X%2010_14_6)%20AppleWebKit%2f537.36%20(KHTML,%20like%20Gecko)%20Chrome%2f96.0.4664.55%20Safari%2f537.36; ti_bm=; user_pref_givenNameLocalLanguage=\"%E6%B3%BD%E8%B1%AA\"; login-check=null; acceleratorSecureGUID=d3d76ad574e466b91f18133422294ab1960a7a1d; auth_session=qmnMdQs4DDBskN_4.y02UFVAQoheHYU6rMoV4nZXL38FnhWNyo636h8iqO8DbRNYuR4U3G7QA4HpM_Kh-NVgn5cHTudk0t1vhqer-BqkoqOtLiUMU_A50Jsa2N05dIeerIN0UQ7udhWPAxvjVIY0Ji7WLrud1JuYqMGlu1nZ_lWEipNxo3cAE_v8Ar9FkpSDpl4UACltUQkJY4QowWllHzsWiKMnsiIK7IEtTbZacbcuvqYjDfOTs76l1smvd52fe-DzM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NJyJDyU-ozse_N1j-yKDvlqRwm6VpqmKRAFS1lH__E5MwhsOnI5kf-dNXvbUkHcMQ0P6XtL8H2IT-OnpYS2hBigTF0yWnGdjCKjb4tjV32xWUFvRByv1JQ_Hg5ei19yEQpCH4xwU2g4VzZhez_68AdpSQ99jsqz4Xbb_c9o6x26B5o3u-vOSpydrBdUFZFPg5BF9j1QhtM4CsRlOfC7i9_kAtzhyFKd1EHUMSvCEJwiqkPN6rMyqrYw5aCxYdFf-WzyCYAZyWhOQTVeBJNq-aTKqb_KiKX_KG3uccXK-d-w4wl-0w3D5qh2qemDAmKfH64YQkWzFX3FdSh2OqZZPMqm7141xQ3CXKTmwxkqv_QHluK6jxU420Q.JDqYuJmklaPm0akAFTjv5A; _gid=GA1.3.1282257837.1638296294; user_pref_givenName=\"Xiaoying\"; login-check=null; bm_sz=73E0FE81A2C50B6265E3EA2B797DB047~YAAQLQrgemkIx0F9AQAAN/BBfg08WbzPEE8d/Bq0+Dj915EOa6nUibLxsE2toOdCwt/HY4EMBDlZ0wfh1Ci1N18L4le0lsiccKQZkuvw/bSJ+GfY3xYX6V/unZpG1LooP627itBD6iQ5d6vNHwxQ9UCul4TLMtA5HsTVEIaSJX3o43hp3I0wcp2f9v9lNEOHNe9OBiZDvRLisoUECdD3DQhXVskTUyXtpAzYW2mlohNUFDOBv0fATlmy9rakQMjukryWc6oNS1G6dpw/IJmifN4xytNzqjiCOEj6kOvddzDmCJKDESI+8RnKi7XCsLctfulO1PC2iwZXjQ/7UP1uWVSdBURQ7lJ62c5iLtbOGHKd0FX559a+P4GdtLPiSzMLUpG6djaDfaKACE8lOEVJhRfa8w==~3158582~3486018; __ar_v4=QFXRHQEHOJDMLHSLFIWCLO%3A20211108%3A22%7C2XNKMR6P4VGD5MD3ZP4SQR%3A20211108%3A22%7CG3YHLXUICZC3XKDXYVVLO4%3A20211108%3A22; da_lid=BCDD00D89A73EA10C5ECBB990C9C75724E|0|0|0; user_pref_permanentId=\"6887527\"; user_pref_uid=\"maze@thunderchip.com\"; last-domain=www.ti.com.cn; tipage=%2Ftistore%2Fproduct%20page%20PINA350ABSIDDFR%20zh; tipageshort=product%20page%20PINA350ABSIDDFR%20zh; ticontent=%2Ftistore; auth_state_BXkqLzjsFI3KG-5CAnVFw8jJcv0=c4BFVRHcFfxbsyEW.yniENl4LbbQaZjeseNUlrUMUSLC9OP_DUcih4Ja5BSNkZ2KiPiYvd-bt7YIDIGZrJY7go9ik7DevNljoH4JeLFet4eZbZn6RU6UPHefzm0Jp8JfW46y1tyYJHSmZAMOuLKS31uvYrfoxKvdbt9PHYrBqhLo3vgPbJCdzQuRowbfMiWJYMeCz0EhSUdyiulFTJmAqUYppYOPbNZH4J8-pp7EX7j0j13XvaPRCmVn18fAD43tY697yELqkSjm23dIqrzdTYoljyZ9cBjMpV5PpiMMf-5FW_KKa36tamkr3SQUY2bQCXU9K148pp-Ko-53W_Qjp3SSFuOxKNTElbOorNkGDudegq0PsaFIACRZ8bAuEF45fiu36H6RgRNbOVhP8bOXxJWYjXTebTc7ioYLyqXN6eAOwYMzAHl8U7Ry8b0kEogdmN2qg2YCNR4lDCVHNtRhyYOkNZSKTpWpP6TA4H7GT.TVk7NgLiR5wVCmERH91zoQ; _abck=C446E9D5801784995040171CCA462AB3~-1~YAAQHwrgeo8+OUd9AQAA7I9HfgZOM2MihuiMhEpROg/gNl1uoKcJQdZZkMl7E83n0rrAOELfxrKl0sUhT373m6nOmnmIIU+5qvYCI0YsAED5kAX7hpLhL1J13MvNb+u0HfiL2IEZ9otkK1z7s1sM+oxf5pfmfh+Cjycf+OdnqIO3YpWkiiizC+nfF2RHETnHmNYCPtMCm+OBssSFiZQNeZV1mAIz+CLneTOwGbFrxERBGTIOd7tI1iSIdW1fWWp59QgI760qRBzPetEDHKk70B7nMwi1E3lloG/DUhlDa3Ffyw3nPq3xtyyJ24MNiMogU4+PcZFy7kjkGXK3lcgPzZxwX3gbVsEygP9AOX70NVVTjv8qQNl9KAKFJJrf9N4zylwedw27+m63Bk03vqfhKWjbh/YFMNvxhAjCqKlxrY60XDcsGSdz/OueW4LsEt5tCnnOJGJcOfD/thovhxI8uiNieg==~-1~-1~-1; ABTasty=uid=bnpbzq1znnf42gn4&fst=1626857731522&pst=1638448362984&cst=1638500797125&ns=63&pvt=509&pvis=5&th=686831.851794.292.20.20.1.1626858218035.1638200937504.1; utag_main=v_id:017ac846ebf20002656c4c7e30890307900df0710093c$_sn:75$_ss:0$_st:1638502947743$free_trial:false$dc_visit:66$channel:organic%3Bexp-1638640546376$ctimestamp:Fri%20Nov%2005%202021%2001%3A55%3A46%20GMT%2B0800%20(%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4)%3Bexp-1638640546376$_pn:5%3Bexp-session$ses_id:1638500796137%3Bexp-session$dc_event:4%3Bexp-session$dc_region:ap-east-1%3Bexp-session; ti_geo=country=CN|city=GUANGZHOU|continent=AS|tc_ip=113.88.97.226; ak_bmsc=25AE9E9B5AAE6DE71ACF8EF0F672183E~000000000000000000000000000000~YAAQ5IvytmOf8yd9AQAAFSXmfg0ipxvJO9MKfULm9ZV7N7rpLGo31cZ2LBjRQG+pz/Izg/bWfm2eWCjRcX6qMFmxw+tg4N3GEP0qH//eJk8bEphiHz87rmnwrK9uNRQ1kKTrUEj0rSXJupADCtq2M55esrTG18oAXV/jmXqQINgtcM+DeQI+am2n4oayPMTRXUdU3i1iy/iOAiF3KWsCqPqmzcOMK9GaYFEI1uxDOYzDr61yq1z1YTzOAwrYvMge3XecdFNem1x69CXUmOKteMAppWx1b0ApUjDdisg/ThF3ErekqNnDRiMX1fBbk+Vwgt/ST2kk19CV4QvssY75a2rvkdvZCg2/IKz8vfAh34FEJ2AcAdaTd58TfdiXKUrIwtw34g3irK8=; bm_sv=D4B3E0A76B30922CC5162078EB582374~5lMrVqCs8L1aeR0fDZC1gEftmPhAaTyaIE554l5G2IHOcKZBJ4P9NkWUXaBxsd7d4FQZW+pIzze4mZLovvncxNoe0zmzbDlKxJYDh8rG4wDgF8cz6iSZ876HxMKevYA9H8pE2RzcmmPEekhtCIqYrH+3wI7+jzbffOmbYmuQkXM=; ti_rid=33a59789"
        //   },
        //   "referrerPolicy": "strict-origin-when-cross-origin",
        //   "body": null,
        //   "method": "GET",
        //   "agent": agent
        // }).then(res => res.json());

        // const str = await got(
        //     'https://www.ti.com.cn/storeservices/cart/opninventory?opn=TLC5916IPWR',
        //     {
        //         headers: {
        //             "cookie": "_ga=GA1.3.477390357.1626857730; ELOQUA=GUID=F915935CD92F4B76B042F6C1601243C6; __adroll_fpc=173589a121e46c49026661b8d685e18d-1626857998685; CONSENTMGR=ts:1633675597897%7Cconsent:true; coveo_visitorId=f2690004-af71-4488-8ae1-835dfb89e48e; _gcl_au=1.1.57629291.1635065929; tiSessionID=lita4c81440a4c81440a4c8144061751ec3340c8ffe; user_pref_shipTo=\"CN\"; user_pref_currency=\"CNY\"; _fbp=fb.2.1636048547960.508365719; user_pref_language=\"zh-CN\"; alias=sys-null-null-cninfra_uhv-bhp-pp-null-cn; ti_ua=Mozilla%2f5.0%20(Macintosh%3b%20Intel%20Mac%20OS%20X%2010_14_6)%20AppleWebKit%2f537.36%20(KHTML,%20like%20Gecko)%20Chrome%2f96.0.4664.55%20Safari%2f537.36; ti_bm=; user_pref_givenNameLocalLanguage=\"%E6%B3%BD%E8%B1%AA\"; login-check=null; acceleratorSecureGUID=d3d76ad574e466b91f18133422294ab1960a7a1d; auth_session=qmnMdQs4DDBskN_4.y02UFVAQoheHYU6rMoV4nZXL38FnhWNyo636h8iqO8DbRNYuR4U3G7QA4HpM_Kh-NVgn5cHTudk0t1vhqer-BqkoqOtLiUMU_A50Jsa2N05dIeerIN0UQ7udhWPAxvjVIY0Ji7WLrud1JuYqMGlu1nZ_lWEipNxo3cAE_v8Ar9FkpSDpl4UACltUQkJY4QowWllHzsWiKMnsiIK7IEtTbZacbcuvqYjDfOTs76l1smvd52fe-DzM1jJvYbkgRFvEw_zPtXrfgWLapR9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VpqmKRAFS1lH__E5MwhsOnI5kf-dNXvbUkHcMQ0P6XtL8H2IT-OnpYS2hBigTF0yWnGdjCKjb4tjV32xWUFvRByv1JQ_Hg5ei19yEQpCH4xwU2g4VzZhez_68AdpSQ99jsqz4Xbb_c9o6x26B5o3u-vOSpydrBdUFZFPg5BF9j1QhtM4CsRlOfC7i9_kAtzhyFKd1EHUMSvCEJwiqkPN6rMyqrYw5aCxYdFf-WzyCYAZyWhOQTVeBJNq-aTKqb_KiKX_KG3uccXK-d-w4wl-0w3D5qh2qemDAmKfH64YQkWzFX3FdSh2OqZZPMqm7141xQ3CXKTmwxkqv_QHluK6jxU420Q.JDqYuJmklaPm0akAFTjv5A; _gid=GA1.3.1282257837.1638296294; user_pref_givenName=\"Xiaoying\"; login-check=null; bm_sz=73E0FE81A2C50B6265E3EA2B797DB047~YAAQLQrgemkIx0F9AQAAN/BBfg08WbzPEE8d/Bq0+Dj915EOa6nUibLxsE2toOdCwt/HY4EMBDlZ0wfh1Ci1N18L4le0lsiccKQZkuvw/bSJ+GfY3xYX6V/unZpG1LooP627itBD6iQ5d6vNHwxQ9UCul4TLMtA5HsTVEIaSJX3o43hp3I0wcp2f9v9lNEOHNe9OBiZDvRLisoUECdD3DQhXVskTUyXtpAzYW2mlohNUFDOBv0fATlmy9rakQMjukryWc6oNS1G6dpw/IJmifN4xytNzqjiCOEj6kOvddzDmCJKDESI+8RnKi7XCsLctfulO1PC2iwZXjQ/7UP1uWVSdBURQ7lJ62c5iLtbOGHKd0FX559a+P4GdtLPiSzMLUpG6djaDfaKACE8lOEVJhRfa8w==~3158582~3486018; __ar_v4=QFXRHQEHOJDMLHSLFIWCLO%3A20211108%3A22%7C2XNKMR6P4VGD5MD3ZP4SQR%3A20211108%3A22%7CG3YHLXUICZC3XKDXYVVLO4%3A20211108%3A22; da_lid=BCDD00D89A73EA10C5ECBB990C9C75724E|0|0|0; user_pref_permanentId=\"6887527\"; user_pref_uid=\"maze@thunderchip.com\"; last-domain=www.ti.com.cn; tipage=%2Ftistore%2Fproduct%20page%20PINA350ABSIDDFR%20zh; tipageshort=product%20page%20PINA350ABSIDDFR%20zh; ticontent=%2Ftistore; auth_state_BXkqLzjsFI3KG-5CAnVFw8jJcv0=c4BFVRHcFfxbsyEW.yniENl4LbbQaZjeseNUlrUMUSLC9OP_DUcih4Ja5BSNkZ2KiPiYvd-bt7YIDIGZrJY7go9ik7DevNljoH4JeLFet4eZbZn6RU6UPHefzm0Jp8JfW46y1tyYJHSmZAMOuLKS31uvYrfoxKvdbt9PHYrBqhLo3vgPbJCdzQuRowbfMiWJYMeCz0EhSUdyiulFTJmAqUYppYOPbNZH4J8-pp7EX7j0j13XvaPRCmVn18fAD43tY697yELqkSjm23dIqrzdTYoljyZ9cBjMpV5PpiMMf-5FW_KKa36tamkr3SQUY2bQCXU9K148pp-Ko-53W_Qjp3SSFuOxKNTElbOorNkGDudegq0PsaFIACRZ8bAuEF45fiu36H6RgRNbOVhP8bOXxJWYjXTebTc7ioYLyqXN6eAOwYMzAHl8U7Ry8b0kEogdmN2qg2YCNR4lDCVHNtRhyYOkNZSKTpWpP6TA4H7GT.TVk7NgLiR5wVCmERH91zoQ; _abck=C446E9D5801784995040171CCA462AB3~-1~YAAQHwrgeo8+OUd9AQAA7I9HfgZOM2MihuiMhEpROg/gNl1uoKcJQdZZkMl7E83n0rrAOELfxrKl0sUhT373m6nOmnmIIU+5qvYCI0YsAED5kAX7hpLhL1J13MvNb+u0HfiL2IEZ9otkK1z7s1sM+oxf5pfmfh+Cjycf+OdnqIO3YpWkiiizC+nfF2RHETnHmNYCPtMCm+OBssSFiZQNeZV1mAIz+CLneTOwGbFrxERBGTIOd7tI1iSIdW1fWWp59QgI760qRBzPetEDHKk70B7nMwi1E3lloG/DUhlDa3Ffyw3nPq3xtyyJ24MNiMogU4+PcZFy7kjkGXK3lcgPzZxwX3gbVsEygP9AOX70NVVTjv8qQNl9KAKFJJrf9N4zylwedw27+m63Bk03vqfhKWjbh/YFMNvxhAjCqKlxrY60XDcsGSdz/OueW4LsEt5tCnnOJGJcOfD/thovhxI8uiNieg==~-1~-1~-1; ABTasty=uid=bnpbzq1znnf42gn4&fst=1626857731522&pst=1638448362984&cst=1638500797125&ns=63&pvt=509&pvis=5&th=686831.851794.292.20.20.1.1626858218035.1638200937504.1; utag_main=v_id:017ac846ebf20002656c4c7e30890307900df0710093c$_sn:75$_ss:0$_st:1638502947743$free_trial:false$dc_visit:66$channel:organic%3Bexp-1638640546376$ctimestamp:Fri%20Nov%2005%202021%2001%3A55%3A46%20GMT%2B0800%20(%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4)%3Bexp-1638640546376$_pn:5%3Bexp-session$ses_id:1638500796137%3Bexp-session$dc_event:4%3Bexp-session$dc_region:ap-east-1%3Bexp-session; ti_geo=country=CN|city=GUANGZHOU|continent=AS|tc_ip=113.88.97.226; ak_bmsc=25AE9E9B5AAE6DE71ACF8EF0F672183E~000000000000000000000000000000~YAAQ5IvytmOf8yd9AQAAFSXmfg0ipxvJO9MKfULm9ZV7N7rpLGo31cZ2LBjRQG+pz/Izg/bWfm2eWCjRcX6qMFmxw+tg4N3GEP0qH//eJk8bEphiHz87rmnwrK9uNRQ1kKTrUEj0rSXJupADCtq2M55esrTG18oAXV/jmXqQINgtcM+DeQI+am2n4oayPMTRXUdU3i1iy/iOAiF3KWsCqPqmzcOMK9GaYFEI1uxDOYzDr61yq1z1YTzOAwrYvMge3XecdFNem1x69CXUmOKteMAppWx1b0ApUjDdisg/ThF3ErekqNnDRiMX1fBbk+Vwgt/ST2kk19CV4QvssY75a2rvkdvZCg2/IKz8vfAh34FEJ2AcAdaTd58TfdiXKUrIwtw34g3irK8=; bm_sv=D4B3E0A76B30922CC5162078EB582374~5lMrVqCs8L1aeR0fDZC1gEftmPhAaTyaIE554l5G2IHOcKZBJ4P9NkWUXaBxsd7d4FQZW+pIzze4mZLovvncxNoe0zmzbDlKxJYDh8rG4wDgF8cz6iSZ876HxMKevYA9H8pE2RzcmmPEekhtCIqYrH+3wI7+jzbffOmbYmuQkXM=; ti_rid=33a59789"
        //         },
        //         agent: {
        //             http: agent,
        //             https: agent
        //         }
        //     }
        // ).json();

        // logger('str', str);

        // continue;

        // return;


        const taskSerials = [];

        let counter = 0;

        let task_index = 0;
        //启动任务
        for (const task of tasks) {
            if (task.status != 1) continue;

            taskSerials.push(task.serial);

            if (!serialMap[task.serial]) {
                serialMap[task.serial] = 1;

                (async (serial, counter) => {
                    if (counter % 10 > 0) {
                        await sleep(counter % 10 * 1000);
                    }

                    //logger('counter', counter);

                    logger(counter, serial, '启动');
                    

                    while (1) {

                        //logger('proxy', serial + ' ' + proxy);

                        if (!serialMap[serial]) {
                            logger(serial, '关闭');
                            return;
                        }
                        let proxy = '';

                        try {

                            proxy = await getProxySlow(serial);

                            if(proxy == ''){
                                logger( serial + 'sleep');
                                await sleep(2000);
                                continue;
                            }else{
                                logger( serial + 'get proxy '+proxy.ip);
                            }

                            const fullUrl = url + encodeURIComponent(serial);
                            let str = '';
                            let ret = '';

                            str = await Promise.race([
                                    httpProxyGet3(fullUrl, proxy.ip),
                                    sleep(16000)
                                ]);

                            //logger('str', str);
                            logger('get '+serial+' result');
                            if(!str){
                                logger( serial + 'sleep2');
                                await update_fail_proxy(proxy.ip, serial);
                                
                                await sleep(2500);
                                continue;
                            }else{
                                logger( str );
                            }
                            
                            ret = str;
                            
                            //logger(ret);

                            const today = sdate.format(new Date(), 'YYYY-MM-DD');
                            const serial_data_key = 'serial_data_'+ today;
                            let serial_data = await hget(serial_data_key, serial);

                            serial_data = JSON.parse(serial_data);

                            if(!serial_data){
                                serial_data = {'serial':task.serial, 'last_stock_num':0, 'last_has_stock_time':'', 'last_check_time':'', 'check_num':0, 'worker':'机器'+arguments[0], 'proxy':proxy};
                            }

                            const stock = ret.inventory;

                            serial_data.last_check_time = sdate.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
                            serial_data.check_num = serial_data.check_num + 1;
                            serial_data.worker = '机器'+arguments[0];
                            serial_data.proxy = proxy.ip;

                            if (stock >= 250) {
                                serial_data.last_has_stock_time = sdate.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
                                serial_data.last_stock_num = stock;
                            }

                            await hset(serial_data_key, serial, JSON.stringify(serial_data));

                            if (stock >= 250) {

                                const success_log_key = 'success_log_'+ today;
                                await lpush(success_log_key, JSON.stringify({'serial':serial, 'stock':stock, 'time':sdate.format(new Date(), 'YYYY-MM-DD HH:mm:ss')}));

                                const msg = `全查方案：规格 ${serial} 发现有 ${stock} 库存可以下单`;
                                if (await avoidNoticeFreq(serial)) {
                                    await easyPushWechatMsg(msg);
                                }
                                logger(msg);

                                try {

                                    const cookie = await get('ti_worker_cookie');

                                    const cmdStr = `curl --compressed -H 'Host: www.ti.com.cn' -H 'Connection: keep-alive' -H 'sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"'  -H 'sec-ch-ua-mobile: ?0'   -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36" -H "Content-Type: application/json" -H 'X-Sec-Clge-Req-Type: ajax' -H 'Expires: 0' -H "Cache-Control: no-store, must-revalidate" -H 'sec-ch-ua-platform: "macOS"' -H 'Accept: */*' -H 'Origin: https://www.ti.com.cn' -H 'Sec-Fetch-Site: same-origin' -H 'Sec-Fetch-Mode: cors' -H 'Sec-Fetch-Dest: empty' -H 'Referer: https://www.ti.com.cn/ordering-resources/buying-tools/quick-add-to-cart.html' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' -H 'Cookie: ${cookie}' -d '{"cartRequestList":[{"packageOption":null,"opnId":"${serial}","quantity":"${stock}","tiAddtoCartSource":"store-pdp","sparam":""}],"currency":"CNY"}'  https://www.ti.com.cn/occservices/v2/ti/addtocart`;

                                    const recentSuccKey = 'ti_add_cart_succ_'+serial;
                                    const isRecentSucc = await get(recentSuccKey);
                                    //最近加购物车是否失败
                                    const recentFailKey = 'ti_add_cart_fail_'+serial;
                                    const isRecentFail = await get(recentFailKey);

                                    if (!isRecentSucc && !isRecentFail) {

                                        ret = await syncExec(cmdStr);


                                        if (ret.indexOf('cartId') > -1 && ret.indexOf('not able to add')<0) {
                                            const msg = `全查方案：${serial}加购物车${stock}成功`;
                                            logger(msg, ret);
                                            //推送微信通知
                                            await easyPushWechatMsg(msg);

                                            //推送到redis，等待下单脚本进行下单操作
                                            await lpush('ti_worker_order', serial);

                                            //记录到redis，最近1小时不再尝试加购物车
                                            await set(recentSuccKey, 1);
                                            await expire(recentSuccKey, 3600);
                                        }else if(ret.indexOf('Access') > -1 && ret.indexOf('Denied') > -1){
                                            if (await avoidNoticeFreqCookie(serial)) {
                                                await easyPushWechatMsg("全查方案：请在后台更换cookie");
                                            }
                                        }else if(ret.indexOf('not able to add') > -1){
                                            if (await avoidNoticeFreqByKey('ti_freq_serial_limit_' + serial)) {
                                                await easyPushWechatMsg("全查方案：${serial}网站限制不给买");
                                            }
                                        }
                                    }

                                    

                                } catch(e) {
                                    logger(e);
                                }
                                await sleep(2000);
                                continue;
                            }
                            await sleep(6000);
                            continue;
                        } catch(e) {
                            logger(e);

                            logger('serial-e', serial);

                            logger('proxy-e', proxy);

                            //let msg = JSON.stringify(e);

                            //if(msg.indexOf('Access') > -1 && msg.indexOf('Denied') > -1){
                                //删除这个proxy
                            await update_fail_proxy(proxy.ip, serial);
                            // }else{
                            // }

                            //logger('9999');

                            //logger('error', serial+' '+proxy);

                            //logger('error', {serial:serial, proxy:proxy});

                            //proxy = await getProxySlow();
                            await sleep(2500);
                            continue;
                        }
                    }
                })(task.serial, counter++);
            }
        }

        //关闭任务
        for (const serial in serialMap) {
            if (taskSerials.indexOf(serial) < 0) {
                delete serialMap[serial];
            }
        }

        await sleep(30000);
    }
})();
